package pinger

import (
	"net"
	"time"

	"golang.org/x/net/ipv4"
	"golang.org/x/net/ipv6"
)

// IsAlive 判断目标主机是否活跃
// 如果不活跃返回 -1
func IsAlive(target string) time.Duration {
	var rtt time.Duration = -1

	addr, err := net.ResolveIPAddr("ip", target)
	if err != nil {
		return rtt
	}

	p := New()
	p.OnRecv = func(r *ReplyInfo) {
		if r.Err != nil {
			return
		}
		if r.ICMPCode != 0 {
			return
		}

		if r.IsIPv6 {
			if r.ICMPType == int(ipv6.ICMPTypeEchoReply) {
				rtt = r.RTT
			}
		} else {
			if r.ICMPType == int(ipv4.ICMPTypeEchoReply) {
				rtt = r.RTT
			}
		}
	}
	p.Ping(addr.IP, 1)

	return rtt
}
